// ListCreator.cs
// ------------------------------------------------------------------
//
// Basic logic that creates the MovieList, synchronously.  It interacts
// with the C4Manager, combines the lists from all disc changers, then
// saves the list to an uncompressed XPS file.
//
// This is used to support non-gui operation.
//
//
// Author     : Dino
// Created    : Sun Oct 23 00:44:52 2011
// Last Saved : <2011-October-26 22:49:21>
//
// ------------------------------------------------------------------
//
// Copyright (c) 2011 by Dino Chiesa
// All rights reserved!
//
// ------------------------------------------------------------------

using System;
using System.IO;
using System.Collections.Generic; // List<T>

namespace C4Tools.ML2
{
    public class ListCreator
    {
        string listXps;

        public ListCreator(string filename)
        {
            this.listXps = filename;
        }

        public void Build()
        {
            var mgr = new C4Tools.AppStateManager<C4Tools.ML2.AppState>("MovieLister2");
            var appState = mgr.GetState();
            if (!String.IsNullOrEmpty(appState.LastControllerIp))
            {
                var c4m = new C4Manager(appState.LastControllerIp);
                if (c4m.IsConnected)
                {
                    var changers = c4m.GetDiscChangerIds();
                    int i = 1;
                    var foundMovies = new List<C4Movie>();
                    changers.ForEach(id => {
                            var range = c4m.GetMoviesOnChanger(id,i++);
                            foundMovies.AddRange(range);
                        });

                    if (foundMovies.Count > 0)
                    {
                        var docBuilder = new DocumentBuilder(null, foundMovies);
                        docBuilder.DoWork(null,null); // synchronous
                        SaveToXpsFile(docBuilder.DocStream);
                    }
                }
            }
        }



        void SaveToXpsFile(Stream content)
        {
            byte[] bytes = new byte[4096];
            int n;
            using (var output = File.Create(this.listXps))
            {
                while((n = content.Read(bytes, 0, bytes.Length)) != 0)
                    output.Write(bytes, 0, n);
            }
            // rewind
            //content.Seek(0, SeekOrigin.Begin);
        }

    }
}
